package com.woyao;

import android.app.Application;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.woyao.core.model.GetMyMessageResponse;
import com.woyao.core.model.KeyValueList;
import com.woyao.core.model.ProfileResponse;
import com.woyao.core.model.Tag;
import com.woyao.core.model.TalkSummary;
import com.woyao.core.model.User;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;
import com.woyao.core.util.StringUtil;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;

import static android.content.Context.MODE_PRIVATE;
import static com.woyao.WoyaoooApplication.userId;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link MessageFragment.OnMessageFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MessageFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MessageFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public UserViewModel uvm;

    FrameLayout theview;
    Toolbar toolbar;
    FrameLayout emptyArea;
    private String type ="";
    private com.woyao.InterestScrollview contentArea;

    private TextView toploading ;
    private TextView bottomloading ;


    private List<TalkSummary> items = new ArrayList<TalkSummary>();
    private boolean nomore = false;
//    private TalkAdapter allAdapter;
    private LinearLayout itemList = null;
//    LinearLayoutManager allLayoutManager = null;

//    private LinearLayout itemList = null;

    private TagAdapter tagAdapter;
    private RecyclerView tagList = null;
    LinearLayoutManager tagLayoutManager = null;
    private Boolean loading = false;

    private Integer ADD_DEMAND_CODE = 2000;

    private Integer MYREGISTER_CODE = 4000;
    private Integer ADD_UPDATE_CODE = 7000;

    private Integer COMPLETE_CATEGORY_CODE = 55;   //



    private OnMessageFragmentInteractionListener mListener;


    public MessageFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MessageFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MessageFragment newInstance(String param1, String param2) {
        MessageFragment fragment = new MessageFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        theview = (FrameLayout) inflater.inflate(R.layout.fragment_message, container, false);

        toolbar = (android.support.v7.widget.Toolbar) theview.findViewById(R.id.toolBar);
////        toolbar.setLogo(R.drawable.ic_launcher);
        toolbar.setTitle("留言");
        toolbar.inflateMenu(R.menu.chance);

        Menu menu = toolbar.getMenu();
        if (menu != null) {
            try {
                //如果不为空,就反射拿到menu的setOptionalIconsVisible方法
                Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                //暴力访问该方法
                method.setAccessible(true);
                //调用该方法显示icon
                method.invoke(menu, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.nav_search) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), SearchActivity.class);
                    startActivity(intent);
                }
                if (item.getItemId() == R.id.nav_change_category) {
                    if (!WoyaoooApplication.hasLogin) {
                        Intent intent = new Intent();
                        intent.setClass(getContext(), RegisterActivity.class);
                        startActivityForResult(intent, MYREGISTER_CODE);
                        return false;
                    }
                    modifyCategory();
                }
                if (item.getItemId() == R.id.nav_publish_demand) {
                    if (!WoyaoooApplication.hasLogin){
                        Intent intent = new Intent();
                        intent.setClass(getContext(), RegisterActivity.class);
                        startActivityForResult(intent,MYREGISTER_CODE);
                        return false;
                    }
//                    if (uvm.getUser().getDemand_id() == 0 ){
                        AddDemand();
//                    }else {
//                        Intent intent = new Intent();
//                        intent.putExtra("id", 0);
//                        intent.putExtra("category", "other");
//                        intent.setClass(getContext(), MoveActivity.class);
//                        startActivityForResult(intent, ADD_UPDATE_CODE);
//                    }
                }


                return false;
            }
        });

        contentArea = (com.woyao.InterestScrollview)theview.findViewById(R.id.content_area);
        contentArea.setChangedHandler(new InterestScrollview.Changed() {
            @Override
            public void Changed(String state) {

                if (state.equals("bottom")){
                    loadData(type,items.size());
                }

                if (state.equals("top")){
                    loadData(type,0);
                }
            }
        });
        emptyArea = (FrameLayout) theview.findViewById(R.id.message_empty_area);
        toploading = (TextView) theview.findViewById(R.id.interest_top_loading);
        bottomloading = (TextView) theview.findViewById(R.id.interest_bottom_loading);

        tagList = (RecyclerView)theview.findViewById(R.id.id_mytags);
        tagLayoutManager = new LinearLayoutManager(getContext());
        tagLayoutManager.setOrientation(OrientationHelper.HORIZONTAL);
        tagList.setLayoutManager(tagLayoutManager);
        tagList.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.HORIZONTAL_LIST));


        itemList = (LinearLayout) theview.findViewById(R.id.items);



//        allLayoutManager = new LinearLayoutManager(getContext());
//        allLayoutManager.setOrientation(OrientationHelper.VERTICAL);
//        itemList.setLayoutManager(allLayoutManager);
//        itemList.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL_LIST));
        if (WoyaoooApplication.hasLogin){

            loadData("",0);
        }

        return theview;
    }
    private Integer addUpdateChoice= 0;

    public  void AddDemand(){
        if (!WoyaoooApplication.hasLogin){
            Intent intent = new Intent();
            intent.setClass(getContext(), RegisterActivity.class);
            startActivityForResult(intent,MYREGISTER_CODE);
            return;
        }


        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        intent.putExtra("is_new", true);
        intent.setClass(getContext(), DemandNewActivity.class);
        startActivityForResult(intent, ADD_DEMAND_CODE);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        uvm = ViewModelProviders.of(getActivity()).get(UserViewModel.class);
    }


    @Override
    public void onResume() {
        super.onResume();

    }

    private void modifyCategory(){
        Intent intent = new Intent();
        intent.putExtra("from", "chance"  );
        KeyValueList kvl = new KeyValueList();
        kvl.setContent( uvm.getUser().getCategory_list() );
        intent.putExtra("category_list", kvl  );
        intent.setClass(getContext(), FilterCategory.class);
        startActivityForResult(intent ,COMPLETE_CATEGORY_CODE);
    }

    private AsyncTask<Void,Void, GetMyMessageResponse> task = null;
    public void loadData( final String kw ,final Integer thenum){
        if(task != null)return;

        if (loading) return;
        loading = true;

        if (thenum == 0){
            toploading.setVisibility(View.VISIBLE);
            bottomloading.setVisibility(View.GONE);
        }else{
            toploading.setVisibility(View.GONE);
            bottomloading.setVisibility(View.VISIBLE);
        }

        if(task != null)return;

        if (thenum == 0){
            items.clear();
        }



        task = new AsyncTask<Void, Void, GetMyMessageResponse>() {
            @Override
            protected GetMyMessageResponse doInBackground(Void... params) {
                AccountService svc = ServiceFactory.get(AccountService.class);
                Call<GetMyMessageResponse> responseCall = svc.getMyTalk(userId,kw,thenum);
                try {
                    GetMyMessageResponse response = responseCall.execute().body();
                    return response;
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(final GetMyMessageResponse response) {

                loading = false;
                if (response != null ) {
                    render(response);
                }
                task = null;
                toploading.setVisibility(View.GONE);
                bottomloading.setVisibility(View.GONE);
            }
            @Override
            protected void onCancelled() {
                loading = false;
                toploading.setVisibility(View.GONE);
                bottomloading.setVisibility(View.GONE);
            }
        };
        task.execute((Void)null);
    }
    private void render(GetMyMessageResponse response){

        if (response.getContent().getStatis().size() == 0){
            tagList.setVisibility(View.GONE);
        }else{
            tagList.setVisibility(View.VISIBLE);
            Integer position = 0 ;
            for (Tag tg : response.getContent().getStatis() ){

                if (tg.getSelected()){
                    break;
                }
                position += 1;
            }
            tagAdapter = new TagAdapter(getContext(),getResources(), response.getContent().getStatis());
            tagAdapter.setChangedHandler(new TagAdapter.Changed() {
                @Override
                public void itemSelected(Tag one) {
                    type = one.getId();
                    loadData(one.getId(),0);
                }
            });

            tagList.scrollToPosition( position );

            tagList.setAdapter(tagAdapter);
        }



        if (response.getContent().getItems().size() == 0  && items.size() ==0 ) {
            contentArea.setVisibility(View.GONE);
            emptyArea.setVisibility(View.VISIBLE);
            return;
        }else{
            emptyArea.setVisibility(View.GONE);
            contentArea.setVisibility(View.VISIBLE);
        }


        if ( response.getContent().getItems().size() ==0 && nomore == false){
            LinearLayout item1 = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.summary_item, null);
            TextView title1 = (TextView) item1.findViewById(R.id.summary_text);
            title1.setText("没有更多了");
            itemList.addView(item1);
            nomore = true;
            return;
        }

        if (items.size() == 0 ){
            itemList.removeAllViews();
        }

//合作的人
        Integer order = items.size();
        for (final TalkSummary curData : response.getContent().getItems()) {
            order = order + 1;

            LinearLayout view = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.message_item, null);

            final TextView theTitle = (TextView) view.findViewById(R.id.chance_title);
            final TextView theSubtitle = (TextView) view.findViewById(R.id.chance_subtext);
            final LinearLayout theContent = (LinearLayout) view.findViewById(R.id.chance_content);
            final CircleImageView theImage = (CircleImageView) view.findViewById(R.id.chance_image);
            final Button theMsg = (Button)  view.findViewById(R.id.chance_msg);
            final TextView theOrder  = (TextView)  view.findViewById(R.id.chance_order);

            theTitle.setText( curData.getTitle() );
            if (curData.getAccess_right().equals("public")){
                theTitle.setTextColor( ContextCompat.getColor(getContext(), R.color.colorTextDarkGrey) );
            }else{
                theTitle.setTextColor( ContextCompat.getColor(getContext(), R.color.colorSubTitleText) );
            }

            theOrder.setText(  order +"") ;

            if (curData.getDescription().equals("")){
                theSubtitle.setVisibility(View.GONE);
            }else {
                theSubtitle.setVisibility(View.VISIBLE);
                theSubtitle.setText(curData.getDescription());
            }

            if (curData.getMessage_num() >0 ) {
                theMsg.setVisibility(View.VISIBLE);
                theMsg.setText(curData.getMessage_num() + "");
            }else{
                theMsg.setVisibility(View.INVISIBLE);
            }

            theImage.setImageResource(R.drawable.no_avartar);
            if (StringUtil.notNullOrEmpty(curData.getSnailview())) {
                Picasso.with(getContext())
                        .load(curData.getSnailview())
                        .into(theImage);
            }

            theContent.setOnClickListener( new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    curData.setMessage_num( 0 );
                    theMsg.setVisibility(View.INVISIBLE);
                    getIt( curData);
                }
            });
            itemList.addView(view);
            View splitter = (View) LayoutInflater.from(getContext()).inflate(R.layout.splitter, null);
            itemList.addView(splitter);
        }
//        allAdapter = new TalkAdapter(getContext(),  items );
//
//        allAdapter.setChangedHandler(new TalkAdapter.Changed() {
//            @Override
//            public void view(TalkSummary r,  View v) {
//                getIt(r ,v);
//            }
//
//
//        });
//
//        itemList.setAdapter(allAdapter);
        items.addAll(  response.getContent().getItems() ) ;

        toolbar.setTitle( response.getContent().getTitle());

    }

    private void getIt( final TalkSummary r  ){

        Intent intent = new Intent();
        intent.setClass(getContext(), TalkActivity.class);
        intent.putExtra("id", r.getId()  );
        intent.putExtra("type", r.getType()  );
        startActivity(intent);


    }



    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onMessageFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnMessageFragmentInteractionListener) {
            mListener = (OnMessageFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    public void loadProfile() {

        final String version = Common.getCurrentVersion(getContext());

        AsyncTask<Void, Void, ProfileResponse> loadTask =
                new AsyncTask<Void, Void, ProfileResponse>() {
                    @Override
                    protected ProfileResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<ProfileResponse> responseCall = svc.getProfile(userId, "android",version);
                        try {
                            ProfileResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(final ProfileResponse response) {
                        if (response != null && response.isSuccess()) {
                            User user = response.getContent();
                            uvm.initUser( user);

                            Application application = getActivity().getApplication();
                            SharedPreferences shared = application.getSharedPreferences("login", MODE_PRIVATE);
                            SharedPreferences.Editor editor = shared.edit();
                            editor.putInt("demand_id", user.getDemand_id());
                            editor.putString("displayname", user.getDisplayname());
                            editor.putString("snailview", user.getSnailview());
                            editor.putString("location", user.getLocation());
                            editor.putString("title", user.getTitle());
                            editor.putString("business", user.getBusiness());
                            editor.putString("business_name", user.getBusiness_name());
                            editor.putInt("member_id", user.getMember_id());
                            editor.putString("mobile", user.getMobile());
                            editor.putString("key", user.getKey());
                            editor.commit();
                            WoyaoooApplication.key = user.getKey();
                            WoyaoooApplication.snailview = user.getSnailview();
                            WoyaoooApplication.displayname = user.getDisplayname();
                            WoyaoooApplication.location = user.getLocation();
                            WoyaoooApplication.title = user.getTitle();
                            WoyaoooApplication.member_id = user.getMember_id();
                            WoyaoooApplication.demand_id = user.getDemand_id();


                            mListener.onMessage(user.getChance_num(), "chance" );
                            mListener.onMessage(user.getMessage_num(), "talk" );
                            mListener.onMessage(user.getCooperate_num(), "cooperate" );
                            mListener.onMessage(user.getPerson_num(), "person" );
                            mListener.onMessage(user.getInterest_num(), "interest" );

                        }
                    }
                };
        loadTask.execute((Void) null);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnMessageFragmentInteractionListener {
        // TODO: Update argument type and name
        void onMessageFragmentInteraction(Uri uri);
        void onMessage( Integer messageNum, String info);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if  (requestCode == MYREGISTER_CODE && resultCode == 666 ){
            loadProfile();
            loadData("",0);

        }


    }
}
